package com.yangtu.nearbyshop.admin.web;

import com.github.pagehelper.PageInfo;
import com.yangtu.nearbyshop.admin.annotation.RequiresPermissionsDesc;
import com.yangtu.nearbyshop.admin.util.AdminResponseCode;
import com.yangtu.nearbyshop.core.util.ResponseUtil;
import com.yangtu.nearbyshop.core.util.bcrypt.BCryptPasswordEncoder;
import com.yangtu.nearbyshop.core.validator.Order;
import com.yangtu.nearbyshop.core.validator.Sort;
import com.yangtu.nearbyshop.db.domain.NearbyshopAdmin;
import com.yangtu.nearbyshop.db.service.NearbyshopAdminService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import com.yangtu.nearbyshop.core.util.RegexUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/admin")
@Validated
public class AdminAdminController {
    private final Log logger = LogFactory.getLog(AdminAdminController.class);

    @Autowired
    private NearbyshopAdminService adminService;

    @RequiresPermissions("admin:admin:list")
    @RequiresPermissionsDesc(menu={"系统管理" , "管理员管理"}, button="查询")
    @GetMapping("/list")
    public Object list(String username,Integer roleId,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        List<NearbyshopAdmin> adminList;
        if(roleId != null){
            adminList = adminService.querySelective(username,1, 10000, sort, order);
            List<NearbyshopAdmin> allList = new ArrayList<>();
            for(NearbyshopAdmin admin: adminList){
                for(Integer rid: admin.getRoleIds()){
                    if(rid.equals(roleId)){
                        allList.add(admin);
                        break;
                    }
                }
            }
            int start = (page-1)*limit;
            if(start>allList.size()){
                adminList = new ArrayList<>();
            }else {
                int end = page * limit - 1;
                if (end > allList.size()) {
                    end = allList.size();
                }
                adminList = allList.subList(start, end);
            }
        }else {
            adminList = adminService.querySelective(username, page, limit, sort, order);
        }
        long total = PageInfo.of(adminList).getTotal();
        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", adminList);

        return ResponseUtil.ok(data);
    }

    private Object validate(NearbyshopAdmin admin) {
        String name = admin.getUsername();
        if (StringUtils.isEmpty(name)) {
            return ResponseUtil.fail("名称");
        }
        if (StringUtils.isEmpty(admin.getEmail())) {
            return ResponseUtil.fail("邮箱");
        }
/*        if (StringUtils.isEmpty(admin.getNickname())) {
            return ResponseUtil.fail("名称");
        }*/
/*        if (!RegexUtil.isUsername(name)) {
            return ResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_NAME, "管理员名称不符合规定");
        }*/
        String password = admin.getPassword();
        if (StringUtils.isEmpty(password) || password.length() < 6) {
            return ResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_PASSWORD, "管理员密码长度不能小于6");
        }
        return null;
    }

    @RequiresPermissions("admin:admin:create")
    @RequiresPermissionsDesc(menu={"系统管理" , "管理员管理"}, button="添加")
    @PostMapping("/create")
    public Object create(@RequestBody NearbyshopAdmin admin) {
        Object error = validate(admin);
        if (error != null) {
            return error;
        }

        String username = admin.getUsername();
        List<NearbyshopAdmin> adminList = adminService.findAdmin(username);
        if (adminList.size() > 0) {
            return ResponseUtil.fail(AdminResponseCode.ADMIN_NAME_EXIST, "管理员已经存在");
        }

        String rawPassword = admin.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodedPassword = encoder.encode(rawPassword);
        admin.setPassword(encodedPassword);
        adminService.add(admin);
        return ResponseUtil.ok(admin);
    }

    @RequiresPermissions("admin:admin:read")
    @RequiresPermissionsDesc(menu={"系统管理" , "管理员管理"}, button="详情")
    @GetMapping("/read")
    public Object read(@NotNull Integer id) {
        NearbyshopAdmin admin = adminService.findById(id);
        return ResponseUtil.ok(admin);
    }

    @RequiresPermissions("admin:admin:update")
    @RequiresPermissionsDesc(menu={"系统管理" , "管理员管理"}, button="编辑")
    @PostMapping("/update")
    public Object update(@RequestBody NearbyshopAdmin admin) {
        Object error = validate(admin);
        if (error != null) {
            return error;
        }

        Integer anotherAdminId = admin.getId();
        if (anotherAdminId == null) {
            return ResponseUtil.badArgument();
        }

        String rawPassword = admin.getPassword();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodedPassword = encoder.encode(rawPassword);
        admin.setPassword(encodedPassword);

        if (adminService.updateById(admin) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok(admin);
    }

    @RequiresPermissions("admin:admin:delete")
    @RequiresPermissionsDesc(menu={"系统管理" , "管理员管理"}, button="删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody NearbyshopAdmin admin) {
        Integer anotherAdminId = admin.getId();
        if (anotherAdminId == null) {
            return ResponseUtil.badArgument();
        }

        adminService.deleteById(anotherAdminId);
        return ResponseUtil.ok();
    }

    @RequiresPermissions("admin:admin:brand")
    @RequiresPermissionsDesc(menu={"系统管理" , "管理员管理"}, button="供应商")
    @GetMapping("/brand")
    public Object brand(String username,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        List<NearbyshopAdmin> adminList = adminService.querySelective(username, page, limit, sort, order);
        List<NearbyshopAdmin> brandList = new ArrayList<>();
        for(NearbyshopAdmin admin : adminList){
            for( Integer roleId : admin.getRoleIds()){
                if(roleId.equals(new Integer(4))){
                    brandList.add(admin);
                }
            }
        }
        Map<String, Object> data = new HashMap<>();
        data.put("total", brandList.size());
        data.put("items", brandList);

        return ResponseUtil.ok(data);
    }
}
